namespace Net8.Identity.WebClient.Extensions
{
    public static class RegisterMiddlewares
    {
        public static WebApplication SetupMiddlewares(this WebApplication app)
        {
            var openIddictClientId = app.Configuration["OpenIddict:ClientId"] ?? "web-client";
            var openIddictClientSecret = app.Configuration["OpenIddict:ClientSecret"] ?? "901564A5-E7FE-42CB-B10D-61EF6A8F3654";
            var openIddictRedirectUri = app.Configuration["OpenIddict:RedirectUri"] ?? "https://localhost:7002/swagger/oauth2-redirect.html";

            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.OAuthClientId(openIddictClientId);
                    c.OAuthClientSecret(openIddictClientSecret);
                    c.OAuthUsePkce();
                    // 允许使用 HTTP（开发环境）
                    c.OAuth2RedirectUrl(openIddictRedirectUri);
                });
                // 异常页面中间件
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // 全局异常处理
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
            // 使用具名 CORS 策略，避免默认策略可能的冲突
            app.UseCors("AllowSwagger");

            // 中间件顺序优化（遵循官方推荐顺序）
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.MapControllers();
            return app;
        }
    }
}